package org.dtrd.modules.device.util;

import org.dtrd.common.util.CheckUtil;
import org.dtrd.common.util.DateUtils;
import org.dtrd.common.util.TimeUtil;
import org.dtrd.config.system.Constant;
import org.dtrd.modules.record.entity.bean.BloodSugar;
import org.dtrd.modules.record.entity.bean.SugarValueBean;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 * 瞬感伴侣蓝牙数据解析
 *
 * @author xiao
 */
public class SGBLBLEParseUtil {

    /**
     * 允许的未来超时时间 单位分钟 ，即 上报的血糖记录时间可以比当前时间超时时长
     */
    public static final int FUTURE_TIME = 30;

    public static List<SugarValueBean> getBloodSugar(String hex) {
        List<SugarValueBean> list = new ArrayList<>();
        String hexTitle = hex.substring(0, 2);
        if (hexTitle.equals("65")) {
            list = getBlood(hex, "timeBloodSugar"); // 时刻血糖
        }
        if (hexTitle.equals("67")) {
            list = getBlood(hex, "pointBloodSugar"); // 点血糖
        }

        return list;
    }

    private static List<SugarValueBean> getBlood(String hex, String bloodSugarType) {
        List<SugarValueBean> list = new ArrayList<>();
        String hexFirst = hex.substring(2, 14);
        String hexSecond = hex.substring(14, 26);
        String hexThird = hex.substring(26, 38);
        if (!hexFirst.equals("303030303030")) {
            BloodSugar bloodSugar = new BloodSugar();
            SugarValueBean sugarValueBean = new SugarValueBean();
            // 12位 为血糖值，4位为标记位，后4字节为测量时间
            String bloodSugarFirstString = hex.substring(2, 5);
            // 十六进制转十进制并计算返回 血糖值

            double bloodSugarFirst = stringTransforBlood(bloodSugarFirstString);
            if (bloodSugarFirst > 0.5 && bloodSugarFirst < 34) {// 判断H L
                // 标记
                String bloodFlagBitFirst = hex.substring(5, 6);
                double bloodTagFirst = Integer.valueOf(bloodFlagBitFirst, 16);
                if (bloodTagFirst == 1) {
                    bloodTagFirst = 9;
                } else {
                    bloodTagFirst = 1;
                }
                // 测量时间
                String bloodTimeStempFirst = hex.substring(6, 14);
                // 转十进制 测量时间
                String bloodTimeStemp = stringTransforInt(bloodTimeStempFirst);
                bloodSugar.setSugarTimeType(getHourFromTime(bloodTimeStemp));

                bloodSugar.setBloodSugarType(bloodSugarType);
                bloodSugar.setBloodSugar(bloodSugarFirst);
                bloodSugar.setBloodFlagBit(bloodFlagBitFirst);
                bloodSugar.setBloodTimeStemp(bloodTimeStemp);
                bloodSugar.setBloodTag(bloodTagFirst);
                list.add(sugarValueBean.buildFromBloodSugar(bloodSugar));
            }
        }
        if (!hexSecond.equals("303030303030")) {
            BloodSugar bloodSugar = new BloodSugar();
            SugarValueBean sugarValueBean = new SugarValueBean();
            // 12位 为血糖值，4位为标记位，后4字节为测量时间
            String bloodSugarSecondString = hex.substring(14, 17);
            // 十六进制转十进制并计算返回 血糖值
            double bloodSugarSecond = stringTransforBlood(bloodSugarSecondString);
            if (bloodSugarSecond > 0.5 && bloodSugarSecond < 34) {// 判断H L
                // 标记
                String bloodFlagBitSecond = hex.substring(17, 18);
                double bloodTagSecond = Integer.valueOf(bloodFlagBitSecond, 16);
                if (bloodTagSecond == 1) {
                    bloodTagSecond = 9;
                } else {
                    bloodTagSecond = 1;
                }
                // 测量时间
                String bloodTimeStempSecond = hex.substring(18, 26);
                // 转十进制 测量时间
                String bloodTimeStempSecond2 = stringTransforInt(bloodTimeStempSecond);
                bloodSugar.setSugarTimeType(getHourFromTime(bloodTimeStempSecond2));
//                if (0 == StringUtil.StrTrimInt(bloodSugar.getSugarTimeType())) {
//                    LogUtil.print("SGBLBLEParseUtil.getBlood.hex=" + hex + "; bloodTimeStempSecond=" + bloodTimeStempSecond
//                            + ";  bloodTimeStempSecond2=" + bloodTimeStempSecond2);
//                }
                bloodSugar.setBloodSugarType(bloodSugarType);
                bloodSugar.setBloodSugar(bloodSugarSecond);
                bloodSugar.setBloodFlagBit(bloodFlagBitSecond);
                bloodSugar.setBloodTimeStemp(bloodTimeStempSecond);
                bloodSugar.setBloodTag(bloodTagSecond);
                list.add(sugarValueBean.buildFromBloodSugar(bloodSugar));
            }
        }
        if (!hexThird.equals("303030303030")) {
            BloodSugar bloodSugar = new BloodSugar();
            SugarValueBean sugarValueBean = new SugarValueBean();
            // 12位 为血糖值，4位为标记位，后4字节为测量时间 十六进制转十进制并计算返回 血糖值
            String bloodSugarThirdString = hex.substring(26, 29);

            double bloodSugarThird = stringTransforBlood(bloodSugarThirdString);
            if (bloodSugarThird > 0.5 && bloodSugarThird < 34) {// 判断H L
                // 标记
                String bloodFlagBitThird = hex.substring(29, 30);
                double bloodTagThird = Integer.valueOf(bloodFlagBitThird, 16);
                if (bloodTagThird == 1) {
                    bloodTagThird = 9;
                } else {
                    bloodTagThird = 1;
                }
                // 转十进制 测量时间 测量时间
                String bloodTimeStempThird = hex.substring(30, 38);
                bloodTimeStempThird = stringTransforInt(bloodTimeStempThird);

                bloodSugar.setSugarTimeType(getHourFromTime(bloodTimeStempThird));
                bloodSugar.setBloodSugarType(bloodSugarType);
                bloodSugar.setBloodSugar(bloodSugarThird);
                bloodSugar.setBloodFlagBit(bloodFlagBitThird);
                bloodSugar.setBloodTimeStemp(bloodTimeStempThird);
                bloodSugar.setBloodTag(bloodTagThird);

                list.add(sugarValueBean.buildFromBloodSugar(bloodSugar));
            }
        }
        return list;
    }

    private static double stringTransforBlood(String bloodSugarStr) {
        double bloodsugar = Integer.valueOf(bloodSugarStr, 16);
        bloodsugar = (double) Math.round(bloodsugar * 0.0555 * 100) / 10.0;
        bloodsugar = (double) Math.round(bloodsugar) / 10.0;
        return bloodsugar;
    }

    public static String stringTransforInt(String timeStemp) {
        long bloodTimeStemp = (long) Integer.valueOf(timeStemp, 16);
        long time = bloodTimeStemp * 1000;
        Timestamp ts = new Timestamp(time);

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String result = simpleDateFormat.format(ts);
        return result;
    }

    /**
     * 根据时间值获取对应索引值
     */
    public static int getTimeTypeIndex(int hour) {
        if (hour >= 0 && hour < 5) {
            // 凌晨
            return Constant.SugarRecordType.EARLYMORNING.getType();
        } else if (hour >= 5 && hour < 9) {
            // 早餐前  空腹
            return Constant.SugarRecordType.BEFOREBREAKFAST.getType();
        } else if (hour >= 9 && hour < 11) {
            // 早餐后
            return Constant.SugarRecordType.AFTERBREAKFAST.getType();
        } else if (hour == 11) {
            // 午餐前
            return Constant.SugarRecordType.BEFORELUNCH.getType();
        } else if (hour >= 12 && hour < 17) {
            // 午餐后
            return Constant.SugarRecordType.AFTERLUNCH.getType();
        } else if (hour >= 17 && hour < 19) {
            // 晚餐前
            return Constant.SugarRecordType.BEFOREDINNER.getType();
        } else if (hour >= 19 && hour < 21) {
            // 晚餐后
            return Constant.SugarRecordType.AFTERDINNER.getType();
        }else {
            // 睡前
            return Constant.SugarRecordType.BEFORESLEEP.getType();
        }
    }

    /**
     * @param time yyyy-MM-dd HH:mm:ss
     * @return
     */
    public static int getHourFromTime(String time) {
        try {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(DateUtils.str2Date(time,DateUtils.datetimeFormat.get()));
            return getTimeTypeIndex(calendar.get(Calendar.HOUR_OF_DAY));
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * 十六进制转ASCII
     *
     * @param hex
     * @return
     */
    public static String convertHexToString(String hex) {

        StringBuilder sb = new StringBuilder();
        StringBuilder temp = new StringBuilder();
        String output;
        int decimal;
        // 49204c6f7665204a617661 split into two characters 49, 20, 4c...
        for (int i = 0; i < hex.length() - 1; i += 2) {
            output = hex.substring(i, (i + 2)).trim();
            decimal = Integer.parseInt(output, 16);
            sb.append((char) decimal);
            temp.append(decimal);
        }
        return sb.toString();
    }

    /**
     * true 超出限定时间
     *
     * @param time
     * @return
     * @author xiao
     * @update [变更日期YYYY-MM-DD][更改人姓名][变更描述]
     * @since 2018年5月26日下午10:43:42
     */
    public static boolean judgeTime(String time) {
        if (CheckUtil.isEmpty(time)) {
            return false;
        }
        String endDate = TimeUtil.getInstance().getStandardDate(DateUtils.datetimeFormat.get().toPattern());
        endDate = TimeUtil.getInstance().dateAdd(FUTURE_TIME, endDate, DateUtils.datetimeFormat.get().toPattern(), Calendar.MINUTE);
        int judgeDate = TimeUtil.getInstance().judgeDate(time, endDate, DateUtils.datetimeFormat.get().toPattern());
        return judgeDate > 0;
    }

    /**
     * 解析瞬感移动版数据记录趋势
     * 原始记录
     * 0x1 即刻血糖趋势 8 无标记
     * 0x2 即刻血糖趋势 A 下降↘
     * 0x3 即刻血糖趋势 B 平稳→
     * 0x4 即刻血糖趋势 C 上升↗
     * 0x5 即刻血糖趋势 D 快速上升↑
     * 0x6 即刻血糖趋势 E 或 9 快速下降↓
     * 0xF 血糖仪血糖
     * 0xE 血糖仪血酮
     * <p>
     * 微信端通知趋势标记 0 下降 1 平稳  2 上升  3 急速上升  4 急速下降 5 血糖仪血糖  6 血糖仪血酮 -1 无标记
     *
     * @param trend
     * @return
     */
    public static int parseTrendency(String trend) {
        int trendency = -1;
        switch (trend) {
            case "2":
                trendency = 0;
                break;
            case "3":
                trendency = 1;
                break;
            case "4":
                trendency = 2;
                break;
            case "5":
                trendency = 3;
                break;
            case "6":
                trendency = 4;
                break;
            case "F":
                trendency = 5;
                break;
            case "E":
                trendency = 6;
                break;
            case "1":
            default:
                break;
        }
        return trendency;
    }
}
